package com.credithc.signature.common.service.lanmao;

import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.constant.SealConstant;
import com.credithc.signature.common.po.SealInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 懒猫印章图片相关业务
 * @author zhanghanqiu
 * @date 2019/10/9 14:46
 */
@Service
@Slf4j
public class LanmaoSignImageService {

    @Value("${cat.sdk.customerNo:911101135769049507A}")
    private String customerNo;

    @Value("${cat.sdk.method.signupMethod:/sign/image/upload}")
    private String signupMethod;

    @Autowired
    private LanmaoSdkClient lanmaoSdkClient;

    /**
     *
     * @param sealInfo
     * @return
     */
    public String updataSignImage(SealInfo sealInfo){

        try {

            if (StringUtils.isBlank( sealInfo.getUserId())){

                return null;
            }
            byte[] fileBytes = sealInfo.getImage();
            String imageData = Base64.encodeBase64String(fileBytes);
            JSONObject body = new JSONObject();
            body.put("userId", sealInfo.getUserId());
            body.put("imageData", imageData);
            body.put("imageId", "");

            JSONObject postData = new JSONObject();
            JSONObject head = new JSONObject();
            head.put("customerNo", customerNo);
            postData.put("head", head);
            postData.put("body", body);
            JSONObject response = lanmaoSdkClient.post(signupMethod, postData);
            JSONObject rshead = response.getJSONObject("head");
            if (!SealConstant.SUCCESS.equals(rshead.get("rspCode"))){
                log.error("userid为{}图片更新失败{}",sealInfo.getUserId(),response.toJSONString());
                throw  new Exception(rshead.toString());
            }
            log.info("userId为{}图片更新成功{}",sealInfo.getUserId(),response.toJSONString());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("系统错误{}",e.getMessage());
        }
        return null;
    }
}
